<template>
  <BasicModal v-bind="$attrs" @register="registerModal" @ok="handleSubmit" :title="getTitle">
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm" />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, computed } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { getAttrList } from './attrData';
  import { UpdateModelGoup, getAddModelGroup } from '/@/api/sys/gateway/gateway';
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      formData: { type: Object },
      device_mode_id: { type: String },
    },
    emits: ['submit', 'register'],
    setup(prop, { emit }) {
      // let listData = ref([]);
      const isUpdate = ref(true);
      const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
        labelWidth: 120,
        schemas: [
          {
            field: 'id',
            component: 'Input',
            label: 'ID',
            show: false,
          },
          {
            field: 'code',
            component: 'Input',
            label: '编码',
            colProps: {
              span: 24,
            },
            defaultValue: '',
            required: true,
          },
          {
            field: 'group_name',
            component: 'Input',
            label: '属性组名称',
            colProps: {
              span: 24,
            },
            defaultValue: '',
            required: true,
          },
        ],
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner((data) => {
        resetFields();
        data && onDataReceive(data);
      });

      let curRowData = ref({});
      const getTitle = computed(() => (!unref(isUpdate) ? '新增分组' : '编辑分组'));
      function onDataReceive(data) {
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        curRowData.value = [];
        if (unref(isUpdate)) {
          setFieldsValue(data.rowData);
          curRowData.value = data.rowData;
        }
      }
      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          if (unref(isUpdate)) {
            let res = await UpdateModelGoup(values);
          } else {
            values.device_mode_id = prop.device_mode_id;
            await getAddModelGroup(values);
          }

          closeModal();
          emit('submit', { isUpdate: unref(isUpdate) });
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, handleSubmit, getAttrList, getTitle };
    },
  });
</script>
